/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import model.Aluno;
import model.Endereco;

/**
 *
 * @author Mera
 */
@WebServlet(name = "FrontController", urlPatterns = {"/FrontController"})
public class FrontController extends HttpServlet {

    private final String URL_WEBSERVICE = "http://localhost:8080/trabalhoWs-2/webresources/aluno";

    private HttpServletRequest request;
    private HttpServletResponse response;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        this.request = request;
        this.response = response;
        String action = request.getParameter("action");

        if ("inserir".equals(action)) {
            inserirAction();
        } else if ("listar".equals(action)) {
            listarAction();
        } else if ("buscar".equals(action)) {
            buscarAction();
        } else if ("editar".equals(action)) {
            editarAction();
        } else if ("remover".equals(action)) {
            removerAction();
        } else {
            dispatchTo("/index.jsp");
        }
    }

    private void inserirAction() throws ServletException, IOException {
        Aluno aluno = buildAluno();
        int idNovoAluno = inserir(aluno);
        if (idNovoAluno != -1) {
            dispatchTo("/ListaAlunos.jsp");
        } else {
            dispatchTo("/index.jsp");
        }
    }

    private int inserir(Aluno aluno) {
        Client client = ClientBuilder.newClient();
        return client.target(URL_WEBSERVICE).request().post(Entity.json(aluno), Integer.class);
    }

    private void listarAction() throws ServletException, IOException {
        Client client = ClientBuilder.newClient();
        List<Aluno> alunos = client.target(URL_WEBSERVICE).request(MediaType.APPLICATION_JSON).get(List.class);
        
        //CONFERE ISSO!
        request.setAttribute("alunos", alunos);
        dispatchTo("/index.jsp");
    }

    private void buscarAction() {
        int id = Integer.parseInt(request.getParameter("matricula"));
        Client client = ClientBuilder.newClient();
        Aluno aluno = client.target(URL_WEBSERVICE + "/" + id).request(MediaType.APPLICATION_JSON).get(Aluno.class);
        
        //DO SOMETHING

    }

    private void editarAction() {
        Aluno aluno = buildAluno();
        Client client = ClientBuilder.newClient();
        int idAlunoEditado = client.target(URL_WEBSERVICE).request().put(Entity.json(aluno), Integer.class);
        
        //DO SOMETHING
    }

    private void removerAction() {
        int idAluno = Integer.parseInt(request.getParameter("matricula"));
        Client client = ClientBuilder.newClient();
        Aluno aluno = client.target(URL_WEBSERVICE + "/" + idAluno).request().delete(Aluno.class);

        //DO SOMETHING
    }

    private Aluno buildAluno() {
        Aluno aluno = new Aluno();
        if (request.getParameter("matricula") != null) {
            aluno.setMatricula(Integer.parseInt(request.getParameter("matricula")));
        }
        aluno.setCpf(request.getParameter("cpf"));
        aluno.setNome(request.getParameter("nome"));
        aluno.setIdade(Integer.parseInt(request.getParameter("idade")));
        aluno.setEndereco(buildEndereco());
        return aluno;
    }

    private Endereco buildEndereco() {
        Endereco endereco = new Endereco();
        if (request.getParameter("id") != null) {
            endereco.setId(Integer.parseInt(request.getParameter("id")));
        }
        endereco.setLogradouro(request.getParameter("logradouro"));
        endereco.setNumero(Integer.parseInt(request.getParameter("numero")));
        endereco.setBairro(request.getParameter("bairro"));
        endereco.setCep(request.getParameter("cep"));
        endereco.setCidade(request.getParameter("cidade"));
        endereco.setEstado(request.getParameter("estado"));
        endereco.setComplemento(request.getParameter("complemento"));
        return endereco;
    }

    private void dispatchTo(String url) throws ServletException, IOException {
        RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
        rd.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
